<?php

namespace App\Http\Controllers\Api;

use App\Models\Comment;
use App\Models\Post;
use App\Notifications\GetNewReplyed;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CommentsController extends ApiController
{

    public function __construct()
    {
        $this->middleware('auth:api');
    }



    /**
     *
     * @api {post} /posts/:post/comments 添加评论
     * @apiName post comments
     * @apiGroup Comments
     *
     * @apiParam {int} post 帖子的id
     * @apiParam {int} content 内容
     * @apiParam {int} image_url 图片链接
     * @apiParam {int} isreply 回复评论的id
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/posts/:post/comments
     *
     */
    public function store(Post $post,Request $request){

        $this->validate($request,[
            'content' => 'required',
            'image_url' => 'url',
            'isreply' => 'exists:posts,id'
        ]);



        $comment = $post->comments()->create(array_merge($request->only([
            'content',
            'image_url',
            'isreply'
        ]),[
            'comment_uid' => Auth::user()->id
        ]));


        $parent_comment = null;
        if ($request->has('isreply')){
            $parent_comment = Comment::find($request->isreply);

        }


        $post->user->notify(new GetNewReplyed($comment,$parent_comment ? $parent_comment : $post));

        return $this->message('评论成功');

    }
}
